package experiment.e07.code;


import java.io.*;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/11/10 14:35
 * @package experiment.e07
 * @description 利用上机6中第3题 的Book类，创建10个相应的对象，写入到文件book2.dat中；
 * 再从文件book2.dat中读出copy到文件book3.dat中。
 */

public class Ch03 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 创建书的数组
        Book[] books = new Book[10];
        books[0] = new Book("859358889", "活着", "余华");
        books[1] = new Book("115319887", "兄弟", "余华");
        books[2] = new Book("495432245", "在风雨中呐喊", "余华");
        books[3] = new Book("134381137", "许三观卖血记", "余华");
        books[4] = new Book("597033817", "一地一鸡毛", "刘震云");
        books[5] = new Book("250305221", "橡皮人", "王朔");
        books[6] = new Book("717876537", "人莫予毒", "王朔");
        books[7] = new Book("180061783", "一句顶一万句", "刘震云");
        books[8] = new Book("4754275478", "文城", "余华");
        books[9] = new Book("563600686", "心力", "邓亚萍");

        File file1 = new File("./src/experiment/e07/code/file/book2.bat.txt");
        File file2 = new File("./src/experiment/e07/code/file/book3.bat.txt");

        // 将book 对象写入到 book2 文件中
        FileOutputStream fos1 = new FileOutputStream(file1);
        ObjectOutputStream oos1 = new ObjectOutputStream(fos1);

        for (Book book : books) {
            oos1.writeObject(book);
        }

        // 将 book2 文件中的对象复制到 book3 文件中
        FileInputStream fis1 = new FileInputStream(file1);
        ObjectInputStream ois = new ObjectInputStream(fis1);

        FileOutputStream fos2 = new FileOutputStream(file2);
        ObjectOutputStream oos2 = new ObjectOutputStream(fos2);

        for (int i = 0; i < books.length; i++) {
            Book book = (Book) ois.readObject();
            System.out.println(book);
            oos2.writeObject(book);
        }

        System.out.println("success");
    }
}

/**
 * Book 类实现Serializable接口
 */
class Book implements Serializable {
    private String isbn;
    private String title;
    private String author;

    public Book(String isbn, String title, String author) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
    }

    public String getIsbn() {
        return isbn;
    }


    public String getTitle() {
        return title;
    }


    public String getAuthor() {
        return author;
    }


    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}